package com.nbsaas.boot.lock.impl;

import com.nbsaas.boot.lock.api.LockService;

import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class ReentrantLockService implements LockService {

    protected final ConcurrentMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        ReentrantLock lock = lockMap.get(key);
        if (lock != null) {
            // 锁已存在，尝试获取锁
            if (lock.isLocked()) {
                return false;
            }
            lock.lock(); // 锁未被占用，获取锁
            return true;
        }

        // 锁不存在时创建并获取
        lock = new ReentrantLock();
        ReentrantLock existingLock = lockMap.putIfAbsent(key, lock);
        if (existingLock != null) {
            // 如果锁已存在，则尝试获取已存在的锁
            if (existingLock.isLocked()) {
                return false;
            }
            existingLock.lock();
            return true;
        }

        // 如果插入锁成功，直接获取锁
        lock.lock();
        return true;
    }

    @Override
    public boolean lock(String key, long timeout, TimeUnit unit) {
        ReentrantLock lock = lockMap.get(key);
        if (lock != null) {
            // 锁已存在，尝试获取锁，带有超时限制
            try {
                return lock.tryLock(timeout, unit);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }

        // 锁不存在时创建新的锁并尝试获取
        lock = new ReentrantLock();
        ReentrantLock existingLock = lockMap.putIfAbsent(key, lock);
        if (existingLock != null) {
            // 锁已被其他线程占用，尝试获取已存在的锁
            try {
                return existingLock.tryLock(timeout, unit);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }

        // 成功插入新锁，尝试获取锁
        try {
            return lock.tryLock(timeout, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean unlock(String key) {
        ReentrantLock lock = lockMap.get(key);
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
            return true;
        }
        return false;
    }


    @Override
    public boolean isLocked(String key) {
        ReentrantLock lock = lockMap.get(key);
        return lock != null && lock.isLocked();
    }
}
